from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from .extensions import db

class User(UserMixin, db.Model):
    """用户模型"""
    __tablename__ = 'user_zhangyiyang'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    join_date = db.Column(db.DateTime, default=datetime.utcnow)
    email_verified = db.Column(db.Boolean, default=False)
    avatar_url = db.Column(db.String(200), default='https://img.picui.cn/free/2025/06/07/684420b9b1cd7.jpg')
    
    # 关联关系
    profile_info = db.relationship('ProfileInfo', backref='user', lazy='dynamic')
    carousel_images = db.relationship('CarouselImage', backref='user', lazy='dynamic')
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)

class EmailCaptcha(db.Model):
    """邮箱验证码模型"""
    __tablename__ = 'email_captcha_zhangyiyang'
    
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), nullable=False)
    captcha = db.Column(db.String(6), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class ProfileInfo(db.Model):
    """个人主页信息模型"""
    __tablename__ = 'profile_info_zhangyiyang'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user_zhangyiyang.id'), nullable=False)
    section_type = db.Column(db.String(50), nullable=False)  # about_me, study, interest, project
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    image_url = db.Column(db.String(200))
    display_order = db.Column(db.Integer, default=0)

class CarouselImage(db.Model):
    """轮播图模型"""
    __tablename__ = 'carousel_images_zhangyiyang'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user_zhangyiyang.id'), nullable=False)
    image_url = db.Column(db.String(200), nullable=False)
    caption = db.Column(db.String(100))
    link_url = db.Column(db.String(200))
    display_order = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True) 